package dump

import system.*;
import app.*;

class DumpController {

	DumpService dumpService = new DumpService();
	String path = Constants.dumpFileDirectory;
	String ext = Constants.dumpFileExt

	def index = {
		redirect(action:list,params:params)
//		fileService.processGLPKFile();
//		redirect(action:list)
	}

	static transactional = true

	def allowedMethods = []

	def list = {
		def fileResourceInstanceList = []
		def f = new File(path)
		if( f.exists() ){
			f.eachFile(){ file->
				if( !file.isDirectory() )
					fileResourceInstanceList.add( file.name )
			}
		}
		fileResourceInstanceList = fileResourceInstanceList.sort()
		[ fileResourceInstanceList: fileResourceInstanceList ]
	}

	def delete = {
		def filename = params.id
		def file = new File( path + File.separatorChar + filename )
		file.delete()
		flash.message = "file ${filename} removed"
		redirect( action:list )
	}


	def download = {
		def filename = params.id;
		def file = new File( path + File.separatorChar + filename );

		try {
			//download
			response.setContentType("application/octet-stream");
			//view
			//response.contentType = "text/plain";
			response.outputStream << file.text;
		}
		catch(Exception e) {
			println(e.message);
		}

		redirect( action:list )
		flash.message = 'file ${filename} downloaded';
	}

	def view = {
		def filename = params.id;
		def file = new File( path + File.separatorChar + filename );
		println(filename)
		//download
		//response.setContentType("application/octet-stream");
		//view
		try
		{
			response.contentType = "text/plain";
			response.outputStream << file.text;
		}
		catch(Exception e)
		{
			println(e.message);
		}
//		redirect( action:list )
	}
	
//	def process = {
//		redirect(action:index)
//	}
	
	def upload = {
		def f = request.getFile('fileUpload')
		if(!f.empty) {
			flash.message = 'Your file has been uploaded'
			new File(path).mkdirs()
			f.transferTo( new File( path + File.separatorChar + f.getOriginalFilename() ) )
		}
		else {
			flash.message = 'file cannot be empty'
		}
		redirect( action:list)
	}
	
	def backup = {
		
		System.out.println(dumpService.backup())
		flash.message = 'Database backed up'
		redirect(action:index)
	}
	
	def restore = {
		String filename = params.id
		System.out.println(dumpService.restore(filename))
		def file = new File( path + File.separatorChar + filename )
		flash.message = "Database restored from file ${filename}"
		redirect( action:list )
	}
}
